import { Injectable, Inject, Optional } from "@angular/core";
import {
  HttpInterceptor,
  HttpHandler,
  HttpRequest
} from "@angular/common/http";
import { APP_CONFIG, AppConfig } from "src/app/app-config";
import { BaseApi } from "src/app/app-api";

@Injectable()
export class UrlFillInterceptor implements HttpInterceptor {
  private baseApi: BaseApi[];

  constructor(@Optional() @Inject(APP_CONFIG) config: AppConfig) {
    if (config && config.baseApi) {
      this.baseApi = config.baseApi;
    }
  }

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    if (
      req.url.startsWith("http") ||
      !this.baseApi ||
      this.baseApi.length === 0
    ) {
      return next.handle(req);
    } else {
      for (const baseApi of this.baseApi) {
        if (req.url.startsWith(baseApi.prefix)) {
          const fullReq = req.clone({
            url: req.url.replace(baseApi.prefix, baseApi.url)
          });
          return next.handle(fullReq);
        }
        // 词典
        if (req.url.startsWith(baseApi.dicPrefix)) {
          const fullReq = req.clone({
            withCredentials: false,
            url: req.url.replace(baseApi.dicPrefix, baseApi.dicUrl)
          });

          return next.handle(fullReq);
        }
        // else if (req.url.startsWith("@")) {
        //   const fullReq = req.clone({
        //     url: req.url.replace("@", baseApi.url)
        //   });
        //   return next.handle(fullReq);
        // }
      }

      return next.handle(req);
    }
  }
}
